package net.moao.netutils;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Toast;

import net.moao.netutils.databinding.ActivityMainBinding;
import net.moao.netutils.utils.AppConfig;
import net.moao.netutils_library.tcp.TCPClient;
import net.moao.netutils_library.tcp.TCPClientThread;
import net.moao.netutils_library.tcp.TCPClientThreadCallback;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Activity mActivity;
    ActivityMainBinding binding;
    TCPClientThreadCallback tcpClientThreadCallback;
    TCPClientThread tcpClientThread;

    /**
     * 初始化 点击事件
     */
    void initOnClick(){
        binding.btnCloseWindow.setOnClickListener(this);
        binding.btnConnect.setOnClickListener(this);
        binding.btnDisConnect.setOnClickListener(this);
        binding.btnSend.setOnClickListener(this);
    }

    /**
     * 初始化数据
     */
    void initData(){
        binding.msg.setMovementMethod(ScrollingMovementMethod.getInstance());   // 设置可以滚动
        binding.btnConnect.setEnabled(true);    // 连接 设置可用
        binding.btnSend.setEnabled(false);
        binding.etIp.setText(AppConfig.getString(mActivity, "ip"));
        binding.etPort.setText(String.valueOf(AppConfig.getInt(mActivity, "port")));
        binding.etMsg.setText(String.valueOf(AppConfig.getString(mActivity, "sendMsg", "abcdefg")));
        tcpClientThreadCallback = new TCPClientThreadCallback() {
            @Override
            public void onConn(boolean isConn) {
                if (isConn){
                    showMsg("连接成功.");
                    runOnUiThread(()->{
                        binding.btnConnect.setEnabled(false);
                        binding.btnSend.setEnabled(true);
                    });
                }else {
                    showMsg("连接失败.");
                }
            }

            @Override
            public void onHeartbeat(TCPClient tcpClient) {
//                tcpClient.send("im alive...");
            }

            @Override
            public void onReceive(byte[] msgBytes) {
                showMsg("RX：" + new String(msgBytes));
            }

            @Override
            public void onRunLast(boolean isConnTCP) {
                showMsg("断开链接.");
                runOnUiThread(()->{
                    binding.btnConnect.setEnabled(true);
                    binding.btnSend.setEnabled(false);
                });
                // 回调函数中 重新初始化 tcpClientThread , 因为 线程只要终止，就没办法重新 start()
                tcpClientThread = new TCPClientThread(false, "192.168.0.8", 2333, 1000, this);
            }
        };
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mActivity = this;
        initOnClick();
        initData();
    }

    /**
     * 当前按钮点击事件
     * @param view 按钮 view
     */
    @Override
    public void onClick(View view) {
        if (view.getId() == binding.btnCloseWindow.getId()){
            finish();
        } else if (view.getId() == binding.btnConnect.getId()){
            AppConfig.putString(mActivity, "ip", binding.etIp.getText().toString());
            try {
                AppConfig.putInt(mActivity, "port", Integer.parseInt(binding.etPort.getText().toString()));
            }catch (Exception e){
                showMsg("端口输入有误，请检查。");
            }
            showMsg("开始链接服务器: " + AppConfig.getString(mActivity, "ip") + AppConfig.getInt(mActivity, "port"));
            tcpClientThread = new TCPClientThread(false, AppConfig.getString(mActivity, "ip"), AppConfig.getInt(mActivity, "port"), 1000, tcpClientThreadCallback);
            tcpClientThread.start();
        } else if (view.getId() == binding.btnDisConnect.getId()) {
            showMsg("开始断开链接服务器...");
            tcpClientThread.interrupt();
        } else if (view.getId() == binding.btnSend.getId()) {
            AppConfig.putString(mActivity, "sendMsg", binding.etMsg.getText().toString());
            if (binding.btnDisConnect.isEnabled()){
                String msg = binding.etMsg.getText().toString();
                try {
                    if (tcpClientThread.send(msg)) {
                        showMsg("TX：" + msg);
                    }else {
                        showMsg("TX：" + msg + "发送失败！");
                    }
                } catch (InterruptedException e) {
                    showMsg("TX：" + msg + "发送失败," + e);
                }
            }else {
                Toast.makeText(this, "请先连接服务器.", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 消息提示框 追加内容 自动滚动到底部
     * @param msg 要提示的信息
     */
    void showMsg(String msg){
        @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
        Date date = new Date();
        String formattedDate = formatter.format(date);
        runOnUiThread(()->{
            // Tv 追加内容
            binding.msg.append(formattedDate + "：" + msg + "\n");
            // 自动滚动
            int offset=binding.msg.getLineCount()*binding.msg.getLineHeight();
            if(offset>binding.msg.getHeight()){
                binding.msg.scrollTo(0,offset-binding.msg.getHeight());
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (tcpClientThread != null){
            tcpClientThread.interrupt();
        }
        super.onDestroy();
    }
}